// import { useState } from 'react'
import { useRef } from 'react'

type Props = {
  onAddTodo: (val: string) => void
}

const TodoAdd = ({ onAddTodo }: Props) => {
  // 使用ref的方式来实现input数据框的操作
  const inputRef = useRef<HTMLInputElement>(null)
  const onKeyDown = (e: React.KeyboardEvent<HTMLInputElement>) => {
    const inputDOM = inputRef.current!
    if (inputDOM.value.trim() === '') return
    if (e.code === 'Enter' || e.code === 'NumpadEnter') {
      onAddTodo(inputDOM.value)
      inputDOM.value = ''
    }
  }

  // 使用受控组件的方式来实现
  // const [value, setValue] = useState('')
  // const onChange = (e: React.ChangeEvent<HTMLInputElement>) => {
  //   setValue(e.target.value)
  // }
  // const onKeyDown = (e: React.KeyboardEvent<HTMLInputElement>) => {
  //   if (value.trim() === '') return
  //   if (e.code === 'Enter' || e.code === 'NumpadEnter') {
  //     onAddTodo(value)
  //     setValue('')
  //   }
  // }
  return (
    <header className='header'>
      <h1>todos</h1>
      <input
        className='new-todo'
        placeholder='What needs to be done?'
        autoFocus
        ref={inputRef}
        // value={value}
        // onChange={onChange}
        onKeyDown={onKeyDown}
      />
    </header>
  )
}

export default TodoAdd
